package com.example.shop.controller;

import com.example.shop.entity.User;
import com.example.shop.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/uploadTx")
    public String uploadTx(@RequestParam("username") String username,@RequestParam(value = "file",required = false) MultipartFile file, HttpServletRequest request){
        try {
            //获取filename
            String filename = file.getOriginalFilename();
            //指定外部存储目录（示例：系统用户目录下的uploads）
            String uploadDir = System.getProperty("user.home") + "/uploads/";
            File dir = new File(uploadDir);
            if (!dir.exists()) dir.mkdirs(); // 创建目录

            // 2. 生成唯一文件名
            String newFilename = UUID.randomUUID()+"_"+filename;

            // 3. 保存文件
            String finalPath = uploadDir + newFilename;
            File targetFile = new File(finalPath);
            file.transferTo(targetFile);
            // 构建可访问的HTTP路径（关键！）将可访问的http路径映射到存在静态目录
            String fileUrl = request.getScheme() + "://" + request.getServerName() +
                    ":" + request.getServerPort() + "/uploads/" + newFilename;

            userService.SetTxUrl(username,fileUrl);
            System.out.println("fileUrl============-----");
            System.out.println(fileUrl);
            return "ok";
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @PostMapping("/login")
    public User login(@RequestBody User user){
        System.out.println("-------------------------------user");
        System.out.println(user);
        return userService.finduser(user);
    }

    @PostMapping("/update")
    public int update(@RequestBody User user){
        System.out.println("----------------要更新的用户信息：" + user); // 打印查看username是否有值
        return userService.update(user);
    }

    @DeleteMapping("/{id}")
    public int delete(@PathVariable int id){
        System.out.println("===============要删除的用户id：" + id);
        return userService.delete(id);
    }

    @GetMapping("/findmul")
    public List<User> findById(Integer id,String username,String tel,String email){
        return userService.findByMul(id,username,tel,email);
    }

    @PostMapping("/adduser")
    public int InsertUser(@RequestBody User user){
        System.out.println("---------------------------------------------");
        System.out.println(user);
        return userService.InsertUser(user);
    }
    @GetMapping("/findpage")
    public Map<String,Object> findPage(@RequestParam int pageSize,@RequestParam int pageNum){
        pageNum = (pageNum-1)*pageSize;
        List<User> users= userService.findPage(pageSize,pageNum);
        int totalUser = userService.totalUser();
        Map<String,Object> result=new HashMap<>();
        result.put("data",users);
        result.put("total",totalUser);
        return result;
    }
}
